#include "kubelet.h"
#include "model.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <jsoncpp/json/json.h>
#include "api_server_client.h"

namespace nanok {

Kubelet::Kubelet(const std::string& node_name, const std::string& api_server)
    : node_name_(node_name), api_server_(api_server), running_(false) {}

void Kubelet::Start() {
    registerNode();
    running_ = true;
    std::thread taskThread(&Kubelet::processTasks, this);
    taskThread.detach();
    std::cout << "Kubelet started on node " << node_name_ << std::endl;
}

void Kubelet::Stop() {
    running_ = false;
}

void Kubelet::registerNode() {
    Node node;
    node.metadata.name = node_name_;
    node.metadata.resourceVersion = 1;
    std::string key = "/nodes/" + node_name_;
    std::string value = to_json(node);
    nanok::registerNode(key, value);
}

void Kubelet::processTasks() {
    while (running_) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        
        try {
            std::vector<Task> tasks;
            nanok::getTasks(tasks);
            for (const auto& task : tasks) {
                if (task.spec.assignedNode == node_name_) {
                    // 获取 Pod 信息
                    std::string podKey = "default/" + task.spec.podName;
                    std::string podJson;
                    Pod pod;
                    nanok::getPod(podKey, pod);
                    if (pod.status.phase != "Running") {
                        // 使用 ctr 命令启动容器
                        if (startContainer(pod)) {
                            // 更新 Pod 状态
                            pod.status.phase = "Running";
                            pod.status.hostIP = "192.168.1.115"; // 简化处理
                            pod.status.podIP = "172.17.0.2";     // 简化处理
                            time_t now = time(0);
                            pod.status.startTime = ctime(&now);
                            pod.metadata.resourceVersion++;
                            std::string updatedPodJson = to_json(pod);
                            std::string fullPodKey = "/pods/default/" + task.spec.podName;
                            updatePod(fullPodKey, updatedPodJson);
                        }
                    }
                }
            }
        } catch (const std::exception& e) {
            std::cerr << "Error in task processor: " << e.what() << std::endl;
        }
    }
}

bool Kubelet::startContainer(const Pod& pod) {
    if (pod.spec.containers.empty()) {
        return false;
    }
    const Container& container = pod.spec.containers[0];
    std::string command = "sudo ctr run -d --net-host registry.access.redhat.com/ubi8/" + 
                         container.image + " " + pod.metadata.name;
    std::cout << command << std::endl;
    int result = system(command.c_str());
    return result == 0;
}

} // namespace nanok